package com.douyin.config;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class MetricsInterceptor implements HandlerInterceptor {

    @Autowired
    private MeterRegistry meterRegistry;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        Long startTime = (Long) request.getAttribute("startTime");
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;
            String uri = request.getMethod() + "_" + request.getRequestURI()
                    .replaceAll("/[0-9]+", "/{id}"); // 替换路径参数

            // 正确创建带标签的计时器
            Timer timer = Timer.builder("api.duration")
                    .tag("uri", uri)
                    .tag("status", String.valueOf(response.getStatus()))
                    .register(meterRegistry);

            timer.record(duration, TimeUnit.MILLISECONDS);
        }
    }
}
